package com.tudouji.framework.task;


import _128._90._114._47.ormrpc.services.WSExportSupplierFacade.WSExportSupplierFacadeSrvProxy;
import _128._90._114._47.ormrpc.services.WSExportSupplierFacade.WSExportSupplierFacadeSrvProxyProxy;
import com.alibaba.fastjson.JSONObject;
import com.tudouji.common.enums.CopyTypeEnums;
import com.tudouji.common.enums.IsCopyEnums;
import com.tudouji.common.enums.KdSupplierKeyEnums;
import com.tudouji.common.utils.StringUtils;
import com.tudouji.common.utils.xml.XmlUtils;
import com.tudouji.project.copy.domain.Copyparam;
import com.tudouji.project.copy.service.ICopyparamService;
import com.tudouji.project.copy.service.impl.KdPostUtils;
import com.tudouji.project.organization.domain.Supplier;
import com.tudouji.project.organization.mapper.SupplierMapper;
import com.tudouji.project.organization.service.ISupplierService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.rmi.RemoteException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * 供應商同步Task
 */
@Slf4j
@Component("supplierSynTask")
public class SupplierSynTask {

    @Autowired
    private ICopyparamService copyparamService;
    @Autowired
    private ISupplierService supplierService;
    @Autowired
    private SupplierMapper supplierMapper;
    @Autowired
    private KdPostUtils kdPostUtils;

    private List<Supplier> supplierList = new ArrayList<>();

    public void supplierSynTask() {
        //1、获取系统同步参数
        Copyparam copyparam = new Copyparam();
        copyparam.setType(CopyTypeEnums.SUPPLIER.getCode());
        copyparam.setIscopy(IsCopyEnums.YES.getCode());
        List<Copyparam> copyparams = this.copyparamService.selectCopyparamList(copyparam);
        //2、获取ERP供應商
        supplierList = this.supplierService.selectSupplierList(new Supplier());
        //3、获取金蝶供應商
        kdPostUtils.login();
        WSExportSupplierFacadeSrvProxy supplierProxy = new WSExportSupplierFacadeSrvProxyProxy();
        try {
            Object[] kdSuppliers = supplierProxy.exportSupplierData(0, Integer.MAX_VALUE);
            int rows = 10;
            int start = Integer.valueOf(copyparams.get(0).getBusinessPrefix());
            System.out.println("供應商同步规则 " + copyparams.get(0).getParam());
            if (kdSuppliers.length > 0) {
                if (kdSuppliers.length == start) {
                    System.out.println("金蝶已同步到最后一条数据，修改同步业务前缀后，可重新同步！");
                    return;
                }
                int pageSize = (kdSuppliers.length - start) / rows + 1;
                for (int i = 0; i < pageSize; i++) {
                    startSyn((start + i * rows), rows, copyparams.get(0));
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * @return
     * @Author shaodong
     * @Description //分頁更新處理
     * @Date 11:51 2021/1/27
     * @Param
     **/
    private void startSyn(int start, int rows, Copyparam copyparam) throws java.rmi.RemoteException {
        WSExportSupplierFacadeSrvProxy supplierProxy = new WSExportSupplierFacadeSrvProxyProxy();
        Object[] kdSuppliers = supplierProxy.exportSupplierData(start, rows);
        Date synTime = new Date();
        //3.1、处理金蝶返回后的数据，组装成json集合
        ArrayList<JSONObject> json_kdSuppliers = new ArrayList<>();
        for (int i = 0; i < kdSuppliers.length; i++) {
            JSONObject kdSupplier = XmlUtils.getXmlAttribute(kdSuppliers[i].toString()
                    , new String[]{KdSupplierKeyEnums.NAME.getCode(), KdSupplierKeyEnums.NUMBER.getCode(), "isInternalCompany"});
            json_kdSuppliers.add(kdSupplier);
        }
        //b)供應商同步规则=1，则ERP系统新增该供應商，完成处理
        String param = copyparam.getParam();
        if (StringUtils.equals(param, "1")) {
            Supplier insertSupplier = new Supplier();
            for (int j = 0; j < json_kdSuppliers.size(); j++) {
                JSONObject kdSupp = json_kdSuppliers.get(j);
                if (kdSupp != null) {
                    insertSupplier.setKingdeenum(kdSupp.getString(KdSupplierKeyEnums.NUMBER.getCode()));
                    List<Supplier> insertSuppliers = supplierService.selectSupplierList(insertSupplier);
                    if (insertSuppliers.size() == 0) {
                        //loading...
                        insertSupplier(insertSupplier, kdSupp, synTime);
                    }
                }
            }

        }
        //c)供應商同步规则=2：
        //i.ERP系统是否有同名、且编号空的供應商存在则认为该供應商和金蝶系统供應商为同一供應商，同步金蝶系统供應商编号
        //ii.ERP系统有同名但编号不同的供應商，同步状态（同步失败）、提示信息（供應商信息同名）写入ERP系统供應商表中
        else if (StringUtils.equals(param, "2")) {
            for (int j = 0; j < supplierList.size(); j++) {
                Supplier updateSupp = supplierList.get(j);
                if (null != updateSupp) {
                    for (int k = 0; k < json_kdSuppliers.size(); k++) {
                        JSONObject kdSupp = json_kdSuppliers.get(k);
                        String name = kdSupp.getString(KdSupplierKeyEnums.NAME.getCode());
                        if (StringUtils.equalsAny(StringUtils.trimLR(name), StringUtils.trimLR(updateSupp.getName()))) {
                            if (StringUtils.isBlank(updateSupp.getKingdeenum())) {
                                updateSupp.setKingdeenum(kdSupp.getString(KdSupplierKeyEnums.NUMBER.getCode()));
                                updateSupplier(synTime, "同步成功", 2, updateSupp);
                            } else {
                                String number = kdSupp.getString(KdSupplierKeyEnums.NUMBER.getCode());
                                if (!StringUtils.equals(number, updateSupp.getKingdeenum())) {
                                    updateSupplier(synTime, "供應商信息同名", 3, updateSupp);
                                }
                            }
                        }

                    }
                }
            }

        }
        //d)ERP系统没有同名供應商，则新增该供應商信息到ERP系统
        /*for (int j = 0; j < json_kdSuppliers.size(); j++) {
            JSONObject kdSupp = json_kdSuppliers.get(j);
            if (kdSupp != null) {
                Supplier insertSupplier = new Supplier();
                insertSupplier.setName(StringUtils.trimLR(kdSupp.getString(KdSupplierKeyEnums.NAME.getCode())));
                List<Supplier> insertSuppliers = supplierService.selectSupplierList(insertSupplier);
                if (insertSuppliers.size() == 0) {
                    //loading...
                    insertSupplier(insertSupplier, kdSupp, synTime);
                }
            }
        }*/

        copyparam.setBusinessPrefix(String.valueOf(start + kdSuppliers.length));
        copyparam.setLastupdatetime(synTime);
        copyparamService.updateCopyparam(copyparam);
    }

    private void updateSupplier(Date synTime, String sychinfo, Integer status, Supplier updateSupp) {
        updateSupp.setSynchinfo(sychinfo);
        updateSupp.setSynchstat(status);
        updateSupp.setSynchtime(synTime);
        supplierMapper.updateSupplier(updateSupp);
    }

    /**
     * @return
     * @Author shaodong
     * @Description //插入供應商
     * @Date 18:20 2021/1/26
     * @Param
     **/
    private void insertSupplier(Supplier insertSupplier, JSONObject kdSupp, Date synTime) {
        insertSupplier.setName(StringUtils.trimLR(kdSupp.getString(KdSupplierKeyEnums.NAME.getCode())));
        insertSupplier.setKingdeenum(kdSupp.getString(KdSupplierKeyEnums.NUMBER.getCode()));
        insertSupplier.setSynchtime(synTime);
        insertSupplier.setSynchstat(2);//同步状态:1-未同步,2-同步成功,3-同步失败
        insertSupplier.setStatus(1);
        insertSupplier.setSynchinfo("同步成功");
        insertSupplier.setCreateTime(synTime);
        if (0 == Integer.valueOf(kdSupp.getString("isInternalCompany"))) {
            insertSupplier.setType(2);
            supplierMapper.insertSupplier(insertSupplier);
        } else {
            insertSupplier.setType(3);
            supplierMapper.insertSupplier(insertSupplier);
        }

    }
}
